package com.micro.edu.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.micro.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${server.port}")
    private Integer port;

    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable String email, @PathVariable String password, @PathVariable String code) {
        return userService.register(email, password, code);
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response, @PathVariable String email, @PathVariable String password) {
        String token = userService.login(email, password);
        Cookie cookie = new Cookie("token", token);  //对比入参数据
        cookie.setPath("/");
        response.addCookie(cookie);
        return token;
    }

    @SentinelResource(blockHandler = "handlerException",fallback="handlerError" )
    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        return userService.info(token);
    }

    public String handlerException () {
        return "handlerException";
    }

    public String handlerError() {
        return "handlerError";
    }

}
